package loggerhelper
import (
"fmt"
"io"
"time"
logrus "github.com/sirupsen/logrus"
)
type FormatType int32
const (
FormatType_JSON FormatType = 0
FormatType_Text FormatType = 1
)
type Options struct {
Type FormatType
DisableTimeField bool
TimeFormat string
Level logrus .Level
DefaultFieldMap logrus .FieldMap
ExtFields map [string ]interface {}
Output io .Writer
Hooks []logrus .Hook
}
var DefaultOpts = Options {
Type : FormatType_JSON ,
TimeFormat : time .RFC3339Nano ,
Level : logrus .DebugLevel ,
DefaultFieldMap : logrus .FieldMap {
logrus .FieldKeyTime : "time" ,
logrus .FieldKeyLevel : "level" ,
logrus .FieldKeyMsg : "event" ,
logrus .FieldKeyLogrusError : "logrus_error" ,
logrus .FieldKeyFunc : "caller" ,
logrus .FieldKeyFile : "file" ,
},
ExtFields : map [string ]interface {}{},
Hooks : []logrus .Hook {},
}
type Option interface {
Apply (*Options )
}
type funcOption struct {
f func (*Options )
}
func (fo *funcOption ) Apply (do *Options ) {
fo .f (do )
}
func newFuncOption (f func (*Options )) *funcOption {
return &funcOption {
f : f ,
}
}
func WithTextFormat () Option {
return newFuncOption (func (o *Options ) {
o .Type = FormatType_Text
})
}
func WithDisableTimeField () Option {
return newFuncOption (func (o *Options ) {
o .DisableTimeField = true
})
}
func WithTimeFormat (TimeFormat string ) Option {
return newFuncOption (func (o *Options ) {
o .TimeFormat = TimeFormat
})
}
func parseLevel (loglevel string ) logrus .Level {
level , err := logrus .ParseLevel (loglevel )
if err != nil {
fmt .Printf ("未知的等级`%s`,使用默认值`Debug`\n" , loglevel )
return logrus .DebugLevel
}
return level
}
func WithLevel (loglevel string ) Option {
return newFuncOption (func (o *Options ) {
o .Level = parseLevel (loglevel )
})
}
func AddHooks (hooks ...logrus .Hook ) Option {
return newFuncOption (func (o *Options ) {
if o .Hooks == nil {
o .Hooks = []logrus .Hook {}
}
o .Hooks = append (o .Hooks , hooks ...)
})
}
func WithDefaultFieldMap (fm logrus .FieldMap ) Option {
return newFuncOption (func (o *Options ) {
o .DefaultFieldMap = fm
})
}
func AddExtField (field string , value interface {}) Option {
return newFuncOption (func (o *Options ) {
if o .ExtFields == nil {
o .ExtFields = map [string ]interface {}{field : value }
} else {
o .ExtFields [field ] = value
}
})
}
func WithExtFields (extFields map [string ]interface {}) Option {
return newFuncOption (func (o *Options ) {
if o .ExtFields == nil || len (o .ExtFields ) == 0 {
o .ExtFields = extFields
} else {
for field , value := range extFields {
o .ExtFields [field ] = value
}
}
})
}
func WithOutput (writer io .Writer ) Option {
return newFuncOption (func (o *Options ) {
o .Output = writer
})
}
The pages are generated with Golds v0.3.6 . (GOOS=darwin GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds .